<template>
  <section class="content clearfix">
    <div class="option">
      <p class="title">品牌查询</p>
      <div class="seach-input">
          品牌名称：
        <el-input class="myinput" 
          placeholder="请输入您要查询的品牌名称"  v-model="brandName"
         style="width:400px;height:40px;line-height:40px">
        </el-input>
          <el-button type="success" class="but-search"  @click="searchBrandName">搜索</el-button>
          <el-button type="info"  @click="changeBrandName">重置</el-button>
          <el-button type="primary" class="addBrand"  data-toggle="modal"
                    data-target="#modal-default" @click="addBrand" v-if="$_has('sys:brand:add')">新增品牌</el-button>
          <el-button type="primary"  @click="allDeleteBrandComfrim()"
                    v-if="$_has('sys:brand:batchDelete')">批量删除</el-button>
      </div>
    </div>
    <!--查询条件end-->
    <!--数据展示-->
     <div class="table clearfix">
        <el-table
          ref="brandLists"
          :data="brandLists"
          tooltip-effect="dark"
          style="width: 100%;font-size:14px;"
          :header-cell-style="{background:'#F5F7FA',height:'60px','line-height':'60px',color:'#606266','font-size':'14px'}"
          @row-click="clickRow" 
          @selection-change="handleSelectionChange">
          <el-table-column  align="center" 
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column prop="brandLogo" label="品牌logo" min-width="10%"  align="center"  >
                    <!-- 图片的显示 -->
                    <template   slot-scope="scope">   
                        <img v-if="scope.row.brandLogo" :src="scope.row.brandLogo" min-width="50" height="50">
                        <img v-else src="@/assets/noPic.png" >
                    </template>         
          </el-table-column> 
          <el-table-column
            prop="brandName"
            label="品牌名称"
          min-width="10%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="brandUrl"
            label="品牌网址"
            min-width="15%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="relationGoodsNum"
            label="相关"
            min-width="15%"
            show-overflow-tooltip  align="center" >
            <template slot-scope="scope1">
                商品: {{scope1.row.relationGoodsNum}}
            </template>
          </el-table-column>
          <el-table-column
          fixed="right"
          label="操作"
          min-width="12%"  align="center" >
          <template slot-scope="scope">
            <div class="myicon-option">
              <i class="el-icon-myedit" title="编辑"  @click="editorBrand(scope.$index,scope.row.id)" data-toggle="modal"
                          data-target="#modal-default" v-if="$_has('sys:brand:edit')"></i>
              <i class="el-icon-mydelete"  title="删除"  @click="deleteBrandComfrim(scope.row.id)"
                          v-if="$_has('sys:brand:delete')" ></i>
                        </div>
          </template>
        </el-table-column>
        </el-table>
        <el-pagination class="page"
            background
            layout="total,prev, pager, next"
            :total="pages.total"
            :pager-count="6"
            :page-size="pages.display"
            @current-change ='pagechange'
            >
        </el-pagination>
      </div>
    <!--数据展示end-->




    <!--新增，编辑弹框star-->
    <el-dialog :title="action=='add'?'新增品牌':'编辑品牌'" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
       <el-form ref="brandFrom" :model="brandFrom" :rules="rules"  label-width="100px" >   
          <el-form-item label="品牌名称:"  prop="brandName">
              <el-input placeholder="请输入品牌名称"  v-model="brandFrom.brandName" style="width:90%"></el-input>
          </el-form-item>
          <el-form-item label="品牌logo:">
	           <div class="border-default" style="width:90%">
	           		<div>
	                <input @change="choosePic($event)" type="file"  style="display: none; opacity: 0" id="file-upload" accept="image/jpg,image/jpeg,image/png,image/gif">
	                <button @click="fileClick()" v-if="brandFrom.brandName" class="btn btn-info upimgbut">点击上传</button>
	                <button @click="fileClick()" v-else class="btn btn-info upimgbut">点击上传</button>
	                <p class="uplaodImgTip">只能上传JPG / PNG文件，且不超过500KB</p>
	              </div>
	            	<div class="maxImg">
	                <img v-if="show" src="@/assets/addPic.png" alt="">
	                <img :src="brandFrom.brandLogo" class="pic" v-else alt="">
	                <i class="delPic el-icon-close" v-if="!show && !readonly"  alt=""
	                      @click="deletePicComfrim"></i>
	              </div>
	           </div>
          </el-form-item>
            <el-form-item label="品牌网址:" prop="brandUrl">
              <el-input placeholder="请输入品牌网址"   v-model="brandFrom.brandUrl" style="width:90%"></el-input>
          </el-form-item>
            <el-form-item label="品牌描述:" prop="brandDesc">
              <el-input placeholder="请输入品牌描述"   type="textarea"  v-model="brandFrom.brandDesc" style="width:90%"></el-input>
          </el-form-item>
          
          <div style="text-align: center;">
            <el-button type="primary"  @click="submitBrand">保存</el-button>
            <el-button  @click="dialogVisible = false">关闭</el-button>
          </div>
      </el-form>
    </el-dialog>
<!--新增，编辑弹框end-->

    <transition name="fade">
      <div v-if="errorShow" class="gritter-notice-wrapper " :class="{'success-notice-wrapper':errorClass}">
        <div id="gritter-item-4" class="gritter-item-wrapper gritter-error" style="" role="alert">
          <div class="gritter-item"><a class="gritter-close" tabindex="1" @click="closeError"><i
            class="fa fa-close"></i></a>
            <div class="gritter-without-image"><span class="gritter-title">{{errorTitle}}</span>
              <p>{{errorMsg}}</p></div>
          </div>
        </div>
      </div>
    </transition>
  </section>

</template>

<script>
  import pagination from '@/components/common/pageComponent'
  import instance from '@/api/index.js'
  import baseURL from '@/js/common/baseURL'
  import axios from 'axios'

  export default {
    name: "BrandManagement",
    data() {
      return {
        imgList: [],
        size: 0,
        brandLists: [],//获取品牌列表数据
        brandParam: {},//查询条件
        brandFrom: {
          brandLogo: '',
          brandName: '',
          brandUrl:'',
          brandDesc:''

        },//添加品牌form表单
        editorBrandItem: [],//获取编辑数据
        checkBoxList: [],//存放选择删除数据ID
        checked: false,
        show: false,
        showLoad:false,
        pages: {
          total: 0,//总页数
          current: 1,//当前页
          display: 10,//显示条数
        },
        brandName: '',
        readonly: false,
        errorShow: false,//错误显示
        errorMsg: '',//错误信息
        errorTitle: '',//错误提示标题
        errorClass: false,//错误样式
        action: "",
        dialogVisible:false, //控制弹框的显示隐藏
        rules: {
          brandName: [
              { required: true, message: '请输入品牌名称', trigger: 'blur' }
             // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
        },
        multipleSelection:[]
        
      }
    },
    
    created() {
      //获取品牌列表数据
      this.getBrandLists();
    },
    methods: {
      //获得当前选中数据
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      goBanck: function () {
        this.$router.go(-1)
      },

      //删除图片
      deletePicComfrim:function(){
        let vm = this;
        vm.$confirm('此操作将删除此品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
          //type: 'warning'
        }).then(() => {
          vm.deletePic();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },

      //删除图片
      deletePic: function () {
        $("#file-upload").val('');
        this.brandFrom.brandLogo = "";
        this.show = true;
      },
      //分页
      pagechange: function (currentPage) {
        this.brandParam.page = currentPage;
        this.pages.current = currentPage;
        this.getBrandLists();
      },

      //获取品牌下拉列表数据
      getBrandLists: function () {
        let vm = this;
        vm.showLoad = true;
        vm.brandParam.page = vm.pages.current;
        vm.brandParam.rows = vm.pages.display;
        vm.pages.display = vm.brandParam.rows;
        instance({
          method: 'post',
          url: '/v1/goods/brand/getList',
          params: vm.brandParam
        }).then(function (data) {
          if (data.data.success) {
            vm.brandLists = data.data.data.list;
            vm.pages.total = data.data.data.total;
            vm.showLoad = false;
          }
        }).catch(function (err) {
        });
      },

      //删除品牌
      deleteBrandComfrim:function(id){
        let vm = this;
        vm.$confirm('此操作将删除商品品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.deleteBrand(id);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })  
      },

      //删除品牌
      deleteBrand: function (id) {
        let vm = this;
        instance({
          method: "post",
          url: '/v1/goods/brand/delete',
          params: {
            id: id
          }
        }).then(function (data) {
          if (data.data.success) {
            vm.getBrandLists();
          }
        })
      },

      //提交品牌表单
      submitBrand: function () {
        let vm = this;
        vm.brandFrom.brandName= vm.brandFrom.brandName.trim();
        vm.brandFrom.brandUrl= vm.brandFrom.brandUrl.trim();
        vm.brandFrom.brandDesc= vm.brandFrom.brandDesc.trim();


        if (this.brandFrom.brandName) {
          instance({
            method: 'post',
            url: '/v1/goods/brand/addOrEdit',
            data: vm.brandFrom
          }).then(function (data) {
            if(data.data.success){
              vm.dialogVisible = false;
              vm.getBrandLists();
            }else{
              this.$message.error(data.data.msg);
            }
          })
        }else {
          this.$message.error('品牌名称不能为空');
          return;
        }
      },
      
      //添加品牌
      addBrand: function () {
        this.dialogVisible = true;
        this.action = 'add';
        this.brandFrom = {
          brandName: "",
          brandUrl: "",
          brandDesc: "",
          brandLogo:"",
          id: ''
        }
        this.show = true;
      },

      //编辑品牌
      editorBrand: function (index, id) {
        this.dialogVisible = true;
        let vm = this;
        this.action = 'edit';
        let brandObj = {};
        this.show = false;
        brandObj = vm.brandLists[index];
        vm.brandFrom = brandObj;
        delete vm.brandFrom.page
        // delete vm.brandFrom.relationGoodsNum
        delete vm.brandFrom.rows
        delete vm.brandFrom.status
        vm.brandFrom.id = id;
      },

      //批量删除
      allDeleteBrandComfrim:function(){
        let vm = this;
        vm.$confirm('此操作将批量删除品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.allDeleteBrand();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },

      //批量删除
      allDeleteBrand: function () {
        let vm = this;
        var ids =[]
        vm.multipleSelection.forEach(function(obj,ind,arr){
           ids.push(obj.id)
        });
        if (vm.multipleSelection.length > 0) {
          instance({
            method: 'post',
            url: '/v1/goods/brand/batchDelete',
            data:{ids:ids},
          }).then(function (data) {
            vm.checkBoxList = [];
            vm.getBrandLists();
          })
        } else {
          this.$message.error('请选择品牌');
          return;
        }
      },

      //全选反选
      checkedAll: function (e) {
        var vm = this;
        vm.checked = e.target.checked;
        if (!vm.checked) { //实现反选
          vm.checkBoxList = [];
        } else { //实现全选
          vm.checkBoxList = [];
          vm.brandLists.forEach(function (item, index) {
            if (index >= 0) {
              vm.checkBoxList.push(item.id);
            }
          });
        }
      },

      //品牌名称查询
      searchBrandName: function (e) {
        this.brandParam.brandName = this.brandName;
        this.getBrandLists();
      },

      //
      changeBrandName: function () {
        this.brandParam.brandName = '';
        this.brandName = '';
        this.getBrandLists();
      },

      //图片上传
      fileClick: function () {
        if (this.brandFrom.brandName) {
          document.getElementById("file-upload").click();
        } else {
          // this.errorClass = false;
          // this.errorShow = true;
          // this.errorTitle = "图片上传错误";
          // this.errorMsg = "品牌名称不能为空！";
          // this.setTime();
          this.$message.error('品牌名称不能为空');
        }
      },

      //关闭信息提示
      closeError: function () {
        this.errorShow = false;
      },

      //定时信息提示
      setTime: function () {
        let vm = this;
        setTimeout(function () {
          vm.errorShow = false;
        }, 2500)
      },

      choosePic: function (e) {
        let vm = this;
        let current_pic = e.target.files[0];
        this.show = false;
        let form = new FormData();
        form.append('file', current_pic, current_pic.name);
        form.append("key", vm.brandFrom.brandName);
        form.append("type", "bands");
        axios({
          method: 'post',
          url: baseURL + '/v1/goods/uploadPic',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: form
        }).then(function (data) {
          if (data.data.code == '9999') {
            vm.$router.push({
              path: '/login',
            });
            return
          }
          if ( data.data.code == '0000') {
            vm.$router.push({
              path: '/401',
            });
            return
          }
          if ( data.data.code == '1111') {
            vm.$router.push({
              path: '/401',
            });
            return
          }
          if (data.data.success){
            vm.brandFrom.brandLogo = data.data.data;
          }
        });
        this.preview_picture(current_pic);
      },
      preview_picture: function (pic) {
        let r = new FileReader();
        r.readAsDataURL(pic);
        r.onload = function (e) {
          $(".pic").attr("src", this.result);
        }
      }
    },
    components: {
      pagination
    }
  }
</script>

<style scoped lang="less"  type='text/css'>
  .imgW{
    width: 120px;
    height: 82px;
    display: flex;
    align-items: center;
    justify-content:center;
    position: relative;
    left: 50%;
    transform: translate(-50%);
  }
  .imgW img{
    height: 100%;
  }



  //v2
.content{
   .option{
      background: #fff;
      padding: 0 20px;
      .title{
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        border-bottom: 1px solid #dddddd;
        margin-bottom: 16px;
        position: relative;
        &::before{
            content: "";
            display: inline;
            height: 30px;
            width: 2px;
            background-color: #67C23A;
            position: absolute;
            left: -20px;
            top: 10px;
        }
      }
 
       
      .seach-input{
        color: #606266;
        font-size:14px;
        padding-bottom: 25px;
        .myinput{
          width: 370px;
          border-radius: 4px;
        }
      }
      button{
           padding: 12px 21px;
           margin:  0 9px;
           border-radius: 4px;
           &.but-search{
              margin-left: 20px;
           }
      }
  }
    .table{
    font-size: 14px;
    margin-top: 30px;
     background: #fff;
     padding:20px;
     clear: both;
     overflow: hidden;
     .page{
      margin: 20px 0 5px;
       float: right;
    }

  .cell{
       display: flex;
      justify-content: center;
      align-items: center;
      .myicon-option{
        font-size: 18px;
        color: #409EFF;
        margin: 6px;
        cursor:pointer;

         i{
          display: inline-block;
          width: 18px;
          height: 18px;
          margin:  0 12px;
          &.el-icon-myedit{
            background:url('../../../assets/img/myEdit.png') no-repeat; 
            background-size: 100%;
          }
           &.el-icon-mydelete{
              background:url('../../../assets/img/myDelete.png') no-repeat; 
              background-size: 100%;
            }
         }
      }
  }

    // .option-icon{
    //   font-size: 18px;
    //   color: #409EFF;
    //   margin: 6px;
    //   cursor:pointer;
    // }
    // .el-icon-myedit:before{
    //     content: '';
    //     width: 18px;
    //     height: 18px;
    //     position: absolute;
    //     top: 39%;
    //     left: 37%;
		//     display: inline-block;
    //     background:url('../../../assets/img/myEdit.png') no-repeat; 
    //     background-size: 100%;
    // }
    //  .el-icon-myedit:before{
    //     content: '';
    //     width: 18px;
    //     height: 18px;
    //     position: absolute;
    //     top: 39%;
    //     left: 37%;
		//     display: inline-block;
    //     background:url('../../../assets/img/myEdit.png') no-repeat; 
    //     background-size: 100%;
    // }
  }
}

.border-default{
	border: none;
	.upimgbut{
	  background-color: #409EFF;
	  width: 96px;
	  height: 40px;
    border-radius: 4px;
    border-color:#409EFF;
	}
	.uplaodImgTip{
		color: #C0C4CC;
		font-size: 14px;
	}
	.maxImg {
		border: 1px solid #E4E7ED;
    padding: 10px;
    position: relative;
    .delPic{
        position: absolute;
        right: -3px;
        top: 9px;
        width: 18px;
        height: 18px;
    }
		img{
      width: 50%;
    }
	}
}


</style>
